﻿using System;
using System.Drawing;
using System.Windows.Forms;
using YArchitech.LIB;

namespace YArchitech.Controls
{
	public static class DataGridViewExtension
	{
		public static string GetText(this DataGridViewCell cell)
		{
			object value = cell.Value;
			if (value == null)
			{
				return "";
			}
			return value.ToString();
		}

		public static int GetIntValue(this DataGridViewCell cell)
		{
			if (cell.ValueType != typeof(int))
			{
				return 0;
			}
			return Convert.ToInt32(cell.Value);
		}

		public static double GetDoubleValue(this DataGridViewCell cell)
		{
			if (cell.ValueType != typeof(double))
			{
				return 0.0;
			}
			return Convert.ToDouble(cell.Value);
		}

		public static void SetValue(this DataGridViewCell cell, double newValue, int precision = 3)
		{
			if (cell == null)
			{
				return;
			}
			cell.Style.NullValue = 0;
			string value = StringTools.DoubleToString(newValue, precision);
			cell.Tag = newValue;
			cell.Value = value;
			cell.ValueType = typeof(double);
		}

		public static void SetValue(this DataGridViewCell cell, int newValue)
		{
			cell.Tag = newValue;
			cell.Value = newValue;
			cell.ValueType = typeof(int);
		}

		public static void SetValue(this DataGridViewCell cell, string newValue)
		{
			cell.Tag = newValue;
			cell.Value = newValue;
			cell.ValueType = typeof(string);
		}

		public static Rectangle GetDisplayRectangle(this DataGridViewCell cell)
		{
			if (cell.DataGridView == null)
			{
				return Rectangle.Empty;
			}
			return cell.DataGridView.GetCellDisplayRectangle(cell.ColumnIndex, cell.RowIndex, false);
		}

		public static DataGridViewCell GetCell(this DataGridView gv, int row, int col)
		{
			if (row > gv.Rows.Count || col > gv.Columns.Count)
			{
				return null;
			}
			return gv.Rows[row].Cells[col];
		}
	}
}
